<template>
  <div class="container-view">

    <!-- header -->
    <div class="container-view-header">
      <!-- 标题 -->
      <h1 class="text-2xl font-bold">评论管理</h1>
      <div
        class="box-border flex flex-wrap justify-between items-center"
      >
        <!-- 搜索 -->
        <div>
          <FormKit
            type="search"
            placeholder="输入关键词进行搜索"
            help="暂未开发"
            prefixIcon="search"
          ></FormKit>
        </div>

        <!-- 筛选 -->
        <div class="flex">
          <!-- 状态 -->
          <DropdownMenu
            :hoverDrop="true"
            label="状态"
            :options="['全部', '待审核', '已过审', '未过审']"
            @change="selectCommentState"
          >
          </DropdownMenu>
        </div>
      </div>
    </div>

    <!-- main -->
    <div class="container-view-main">
      <MonospacedList
        class="grow w-full overflow-x-auto overflow-y-hidden"
        direction="col"
      >
        <li
          class="shrink-0 min-w-max h-24 max-h-24 flex flex-row gap-4 items-center justify-between p-4 border-b"
          v-for="(item, index) in commentDataSource"
          :key="index"
        >
          <!-- 左侧 -->
          <div class="grow flex flex-row items-center gap-4">
            <!-- 勾选 -->
            <div>
              <input
                type="checkbox"
                class="checkbox checkbox-info [--chkfg:white]"
              />
            </div>
            <!-- 内容 -->
            <div class="grow flex items-center gap-6">
              <!-- commenter头像 -->
              <div class="w-16 h-16 border rounded-lg overflow-hidden">
                <img
                  class="max-w-full max-h-full"
                  :src="'/avatar/email/' + item.commenter_email"
                  alt="avatar"
                />
              </div>
              <!-- 昵称邮箱 -->
              <div class="w-32">
                <div
                  class="w-full overflow-hidden overflow-ellipsis whitespace-nowrap"
                >
                  <span class="font-bold" :title="item.commenter">
                    {{ item.commenter }}
                  </span>
                </div>
                <div
                  class="w-full overflow-hidden overflow-ellipsis whitespace-nowrap"
                >
                  <span class="text-gray-500" :title="item.commenter_email">
                    {{ item.commenter_email || "无" }}
                  </span>
                </div>
              </div>
              <!-- 来源与内容 -->
              <div class="shrink-0">
                <!-- 来源 -->
                <div class="flex gap-2 items-center max-w-80">
                  <span class="badge badge-outline min-w-14">文章</span>
                  <div
                    class="w-full overflow-hidden overflow-ellipsis whitespace-nowrap"
                  >
                    <a
                      class="text-xl font-bold"
                      :title="item.article_title || item.article?.title"
                      :href="
                        websiteURL + '/pages/article.html?id=' + item.article_id
                      "
                      target="_blank"
                    >
                      {{ item.article_title || item.article?.title }}
                    </a>
                  </div>
                </div>
                <!-- 内容 -->
                <div
                  class="max-w-80 overflow-hidden overflow-ellipsis whitespace-nowrap"
                >
                  <p>{{ item.content.substring(0, 20) }}</p>
                </div>
              </div>
            </div>
          </div>
          <!-- 右侧 -->
          <div class="shrink-0 flex items-center justify-center gap-4">
            <time class="text-center" datetime="">{{
              new Date().toLocaleString()
            }}</time>
            <DaisyDropdown
              :options="['查看全文', 'pass', 'reject', 'delete']"
              @select="selectCommentOprationMenuItem($event, index)"
              :top="index === commentPageSize - 1 ? true : false"
              :end="true"
            >
              <template #label>
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  fill="none"
                  viewBox="0 0 24 24"
                  class="inline-block h-5 w-5 stroke-current"
                >
                  <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M5 12h.01M12 12h.01M19 12h.01M6 12a1 1 0 11-2 0 1 1 0 012 0zm7 0a1 1 0 11-2 0 1 1 0 012 0zm7 0a1 1 0 11-2 0 1 1 0 012 0z"
                  ></path>
                </svg>
              </template>
            </DaisyDropdown>
          </div>
        </li>
      </MonospacedList>
    </div>

    <!-- footer -->
    <div class="container-view-footer">
      <div>
        共
        <span>{{ commentCount }}</span>
        条数据
      </div>
      <div class="flex flex-wrap gap-2 items-center">
        <!-- 上下页 -->
        <div class="flex gap-1">
          <button
            class="btn btn-sm btn-outline"
            @click="currentPage > 1 ? currentPage-- : false"
          >
            &lt;
          </button>
          <button
            class="btn btn-sm btn-outline"
            @click="currentPage < commentPageCount ? currentPage++ : false"
          >
            &gt;
          </button>
        </div>
        <!-- 当前页选择 -->
        <div class="flex gap-2 items-center justify-center">
          <div>
            <FormKit
              type="select"
              :options="pageSelectOptions"
              v-model="currentPage"
            ></FormKit>
          </div>
          <span>页</span>
        </div>
        <!-- 每页条数 -->
        <div class="flex gap-2 items-center justify-center">
          <div>
            <FormKit
              type="select"
              :options="[
                { label: '10', value: 10 },
                { label: '20', value: 20 },
                { label: '30', value: 30 },
                { label: '50', value: 50 },
                { label: '100', value: 100 },
              ]"
              v-model="commentPageSize"
            ></FormKit>
          </div>
          <span>条每页</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import MonospacedList from "@/components/monospaced-list/MonospacedList.vue";
import DaisyDropdown from "@/components/daisy-dropdown/DaisyDropdown.vue";
import { FormKit } from "@formkit/vue";
import { ref, computed, watch } from "vue";
import { ResponseStatus } from "@/api/request";
import commentAPI from "@/api/comment";
import { useConfigurationStore } from "@/stores/stores";
import { useDaisyLoading } from "@/components/daisy-loading/daisy.loading";
const daisyLoading = useDaisyLoading();

const websiteURL = ref("");
useConfigurationStore()
  .getConfiguration()
  .then((c) => {
    if (c.website.url.endsWith("/")) {
      c.website.url = c.website.url.substring(0, c.website.url.length - 1);
    }
    websiteURL.value = c.website.url;
  });
const currentPage = ref(1);
const commentSelectState = ref("all");

const commentPageSize = ref(10);
const commentCount = ref(0);
const commentPageCount = computed(() => {
  return Math.ceil(commentCount.value / commentPageSize.value) || 1;
});

const commentDataSource = ref([]);
const pageSelectOptions = ref([]);

async function refreshCount() {
  const result = await commentAPI.getArticleCommentCount(
    commentSelectState.value,
  );
  commentCount.value = result.data;

  pageSelectOptions.value = new Array(commentPageCount.value);
  for (let i = 0; i < commentPageCount.value; i++) {
    const ip1 = i + 1;
    pageSelectOptions.value[i] = {
      label: ip1 + "/" + commentPageCount.value,
      value: ip1,
    };
  }
}
async function refreshData() {
  daisyLoading.showLoading();
  await refreshCount();
  commentAPI
    .getArticleCommentsByPage(
      commentSelectState.value,
      currentPage.value,
      commentPageSize.value,
    )
    .then((result) => {
      commentDataSource.value = result.data;
      daisyLoading.hideLoading();
    });
}
refreshData();

watch(currentPage, (nv, ov) => {
  if (nv !== ov) {
    refreshData();
  }
});
watch(commentPageSize, (nv, ov) => {
  if (nv !== ov) {
    refreshData();
  }
});
watch(commentSelectState, (nv, ov) => {
  if (nv !== ov) {
    refreshData();
  }
});

function selectCommentState(index) {
  if (index === 0) {
    commentSelectState.value = "all";
  } else if (index === 1) {
    commentSelectState.value = "reviewing";
  } else if (index === 2) {
    commentSelectState.value = "pass";
  } else if (index === 3) {
    commentSelectState.value = "reject";
  } else {
    commentSelectState.value = "all";
  }
  console.log("selectCommentState", commentSelectState.value);
}
async function selectCommentOprationMenuItem(arg, commentIndex) {
  const itemIndex = arg.index;
  if (typeof itemIndex !== "number") {
    return;
  }

  const comment = commentDataSource.value[commentIndex];
  console.log(
    "selectCommentOprationMenuItem",
    "item-" + itemIndex,
    "comment-" + comment.id,
  );
  if (itemIndex === 0) {
    // 查看全文
    alert(comment.content);
  } else if (itemIndex === 1) {
    // 通过
    if (!comment.state || comment.state === "pass") {
      alert("该评论已通过，无法再次通过");
      return;
    }
    const notifyPublisher = window.confirm("是否通知文章发布者");
    let notifyParentCommenter = false;
    if (comment.parent_id) {
      notifyParentCommenter = window.confirm("是否通知被回复者");
    }
    const passResult = await commentAPI.passComment(
      comment.id,
      notifyPublisher,
      notifyParentCommenter,
    );
    if (passResult.status === ResponseStatus.SUCCESS) {
      refreshCount();
      commentDataSource.value[commentIndex].state = "pass";
      if (
        commentSelectState.value === "reviewing" ||
        commentSelectState.value === "reject"
      ) {
        commentDataSource.value.splice(commentIndex, 1);
      }
    }
    alert(passResult.message);
  } else if (itemIndex === 2) {
    // 拒绝
    if (comment.state === "reject") {
      alert("该评论已拒绝，无法再次拒绝");
      return;
    }
    const rejectResult = await commentAPI.rejectComment(comment.id);
    if (rejectResult.status === ResponseStatus.SUCCESS) {
      refreshCount();
      commentDataSource.value[commentIndex].state = "reject";
      if (
        commentSelectState.value === "reviewing" ||
        commentSelectState.value === "pass"
      ) {
        commentDataSource.value.splice(commentIndex, 1);
      }
    }
    alert(rejectResult.message);
  } else if (itemIndex === 3) {
    // 删除
    if (!window.confirm("是否删除？")) {
      return;
    }
    const deleteResult = await commentAPI.deleteArticleCommentByID(comment.id);
    if (deleteResult.status === ResponseStatus.SUCCESS) {
      refreshCount();
      commentDataSource.value.splice(commentIndex, 1);
    }
    alert(deleteResult.message);
  }
}
</script>
